<script setup lang="ts">
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useViewportStore } from '@renderer/stores/viewport'
import { Clock } from 'three'

const objects = ref(0)
const vertices = ref(0)
const triangles = ref(0)
const frametime = ref(0)

const viewportStore = useViewportStore()
const { publicGroup } = storeToRefs(viewportStore)

function initCount() {
  objects.value = 0
  vertices.value = 0
  triangles.value = 0
}

function update() {
  if (publicGroup.value) {
    publicGroup.value.children.forEach((object) => {
      object.traverse(function (item: any) {
        if (item.isMesh || item.isPoints) {
          objects.value++
          const geometry = item.geometry
          vertices.value += geometry.attributes.position.count
          if (item.isMesh) {
            if (geometry.index !== null) {
              triangles.value += geometry.index.count / 3
            } else {
              triangles.value += geometry.attributes.position.count / 3
            }
          }
        }
      })
    })
  }
}
// 计算帧数
const clock = new Clock()
let frameCount = 0
let elapsedTime = 0
function animate() {
  initCount()
  update()
  const delta = clock.getDelta()
  elapsedTime += delta
  frameCount++
  if (elapsedTime >= 1.0) {
    const fps = frameCount / elapsedTime
    frametime.value = Math.round(fps)
    elapsedTime = 0
    frameCount = 0
  }
  requestAnimationFrame(animate)
}

setTimeout(() => {
  animate()
})
</script>

<template>
  <div class="viewport-info">
    <div>
      <span class="info-left">{{ objects }}</span>
      <span class="info-right">物体</span>
    </div>
    <div>
      <span class="info-left">{{ vertices }}</span>
      <span class="info-right">顶点</span>
    </div>
    <div>
      <span class="info-left">{{ triangles }}</span>
      <span class="info-right">三角形</span>
    </div>
    <div>
      <span class="info-left">{{ frametime }}</span>
      <span class="info-right">帧数</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.viewport-info {
  position: absolute;
  left: 10px;
  bottom: 20px;
  font-size: 12px;
  color: rgb(255, 255, 255);
  text-transform: lowercase;

  .info-left {
    display: inline-block;
    text-align: right;
    width: 60px;
    margin-right: 6px;
  }

  .info-right {
    display: inline-block;
  }
}
</style>
